package com.simplecontact.activities;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.simplecontact.R;
import com.simplecontact.classes.Reflect;

public class ActCameraScreen extends Activity implements SurfaceHolder.Callback {

	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	private Object mCamera;
	private boolean mPreviewRunning;
	private Button mbtn;
	private int index;

	/**
	 * This function help to determine approriate size
	 * */
	private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {

	        final double ASPECT_TOLERANCE = 0.05;
	        double targetRatio = (double) w / h;
	        if (sizes == null) return null;

	        Size optimalSize = null;
	        double minDiff = Double.MAX_VALUE;

	        int targetHeight = h;

	        for (Size size : sizes) {
	            double ratio = (double) size.width / size.height;
	            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
	            if (Math.abs(size.height - targetHeight) < minDiff) {
	                optimalSize = size;
	                minDiff = Math.abs(size.height - targetHeight);
	            }
	        }
	        if (optimalSize == null) {
	            minDiff = Double.MAX_VALUE;
	            for (Size size : sizes) {
	                if (Math.abs(size.height - targetHeight) < minDiff) {
	                    optimalSize = size;
	                    minDiff = Math.abs(size.height - targetHeight);
	                }
	            }
	        }
	        return optimalSize;
	    }
	
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		if (mPreviewRunning) {
			((Camera) mCamera).stopPreview();
		}
		Camera.Parameters p = ((Camera) mCamera).getParameters();
		 //MODIFIED HERE
        List<Size> sizes = Reflect.getSupportedPictureSizes(p);
        //List<Size> sizes = parameters.getSupportedPreviewSizes();
        Size optimalSize = getOptimalPreviewSize(sizes, width, height);
        p.setPreviewSize(optimalSize.width, optimalSize.height);        

        ((Camera) mCamera).setParameters(p);	
		try {			
			((Camera) mCamera).setPreviewDisplay(holder);
		} catch (IOException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		((Camera) mCamera).startPreview();
		mPreviewRunning = true;
	}

	public void surfaceCreated(SurfaceHolder holder) {
		mCamera = Camera.open();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		((Camera) mCamera).stopPreview();
		mPreviewRunning = false;
		((Camera) mCamera).release();
	}
	
	/**
	 * This is a interface handling taking photos
	 * */
	Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
		public void onPictureTaken(byte[] imageData, Camera c) {
			if(imageData!=null){						
				setResult(RESULT_OK,new Intent().putExtra("image_array", imageData).putExtra("index", index));
				finish();
			}
			else{
				setResult(RESULT_CANCELED);
				finish();
			}
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);

		index = getIntent().getIntExtra("index", 0);
		
		getWindow().setFormat(PixelFormat.TRANSLUCENT);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

		WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.camera_surface);

		mbtn = (Button)findViewById(R.id.btnget);
						
		mbtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				mbtn.setEnabled(false);
				((Camera) mCamera).takePicture(null,null, mPictureCallback);				
			}
		});
		
		mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);

		mSurfaceHolder = mSurfaceView.getHolder();

		mSurfaceHolder.addCallback(this);

		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);	
	}		
}